﻿using System;
using System.Configuration;
using Nancy;
using Nancy.Hosting.Self;
namespace  Famofo.AgbaraVOIP.Rest.FreeSwitch
{
    public class RestServer : RestApi
    {
        private string fs_host =string.Empty;
        private int fs_port = 0;
        private string fs_password = string.Empty;
        private string fs_out_address = string.Empty;
        private string auth_id = string.Empty;
        private string auth_token = string.Empty;
        private string default_http_method = string.Empty;
        private string rest_server_address = string.Empty;
        private bool _run;
        NancyHost nancyHost;
        public RestServer()
        {
            AppSettingsReader reader = new AppSettingsReader();
            fs_host = (string)reader.GetValue("Fs_Inbound_Host", fs_host.GetType());
            fs_port = (int)reader.GetValue("Fs_Inbound_Port", fs_port.GetType());
            fs_password = (string)reader.GetValue("Fs_Inbound_Password", fs_password.GetType());
            fs_out_address = (string)reader.GetValue("Fs_Outbound_Address", fs_out_address.GetType());
            auth_id = (string)reader.GetValue("Auth_Id", auth_id.GetType());
            auth_token = (string)reader.GetValue("Auth_Token", auth_token.GetType());
            default_http_method = (string)reader.GetValue("Default_Http_Method", default_http_method.GetType());
            
            
            inboundsocket = new RESTInboundSocket(fs_host, fs_port, fs_password, fs_out_address, auth_id, auth_token, default_http_method);
            _run = true;
        }

        public void stop()
        {
            _run = false;
            inboundsocket.exit();
        }
        public void start()
        {
            
            try
            {
                int retries = 1;
                
                //while (_run)
                //{
                    
                    try
                    {
                        inboundsocket.connect();
                        inboundsocket.serve_forever();
                        Console.WriteLine("Connected");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error connecting...");
                    }

                    //int sleep_for = retries * 10;
                    ////log reconnecting
                    //System.Threading.Thread.Sleep(sleep_for);
                    //if (retries < 12)
                    //    retries += 1;
                //}
            }
            catch (Exception ex)
            {
            }
        }

    }
}
